package com.jingjin.humanityservice.util.ranking;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jingjin.humanityservice.util.ranking.cacheData.CacheDataInRedis;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Component
public class BaiduRankingHandler {

    private static final HttpClient httpClient = HttpClient.newHttpClient();

    @Resource
    private ObjectMapper objectMapper;

    @Resource
    private CacheDataInRedis cacheDataInRedis;


    public Map<String, Object> handleRoute(Map<String, String> queryParams, boolean noCache) throws Exception {
        String type = queryParams.getOrDefault("type", "realtime");
        Map<String, Object> listResult = getList(type, noCache);

        Map<String, Object> routeData = new LinkedHashMap<>();
        routeData.put("name", "baidu");
        routeData.put("favicon", "https://www.baidu.com/favicon.ico");
        routeData.put("title", "百度");
        Instant nowTime = Instant.now();
        // 将当前时间戳转换为上海时区
        ZonedDateTime Shanghai = nowTime.atZone(ZoneId.of("Asia/Shanghai"));
        routeData.put("nowTime", Shanghai);
        routeData.put("type", "热搜榜");
        routeData.put("link", "https://top.baidu.com/board");
        routeData.put("total", ((List<?>) listResult.get("data")).size());

        List<Map<String, Object>> dataList = addIndexToDataList((List<Map<String, Object>>) listResult.get("data"));
        routeData.put("data", dataList);

        // 缓存数据进redis
        cacheDataInRedis.cacheData("baidu:hotSearch", routeData);

        return routeData;
    }

    private List<Map<String, Object>> addIndexToDataList(List<Map<String, Object>> dataList) {
        return IntStream.range(0, dataList.size())
                .mapToObj(index -> {
                    Map<String, Object> newItem = new LinkedHashMap<>();
                    newItem.put("index", index+1);
                    newItem.putAll(dataList.get(index));
                    return newItem;
                })
                .collect(Collectors.toList());
    }

    private Map<String, Object> getList(String type, boolean noCache) throws Exception {
        String url = "https://top.baidu.com/board?tab=" + type;

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 14_2_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) FxiOS/1.0 Mobile/12F69 Safari/605.1.15")
                .build();

        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        String body = response.body();

        Pattern pattern = Pattern.compile("<!--s-data:(.*?)-->", Pattern.DOTALL);
        Matcher matcher = pattern.matcher(body);
        if (!matcher.find()) {
            throw new RuntimeException("Failed to find data in the response");
        }

        String jsonData = matcher.group(1);
        JsonNode jsonNode = objectMapper.readTree(jsonData);
        JsonNode contentNode = jsonNode.path("cards").get(0).path("content");

        List<Map<String, Object>> list = objectMapper.convertValue(contentNode, new TypeReference<List<Map<String, Object>>>() {});

        List<Map<String, Object>> mappedList = list.stream().map(v -> {
            Map<String, Object> item = new LinkedHashMap<>();
            item.put("title", v.get("word"));
            item.put("url", "https://www.baidu.com/s?wd=" + encodeURIComponent(v.get("query") != null ? v.get("query").toString() : ""));
            item.put("mobileUrl", v.get("rawUrl") != null ? v.get("rawUrl") : "");

            return item;
        }).collect(Collectors.toList());

        Map<String, Object> result = new HashMap<>();
        result.put("fromCache", false);
        result.put("updateTime", System.currentTimeMillis());
        result.put("data", mappedList);

        return result;
    }

    private String encodeURIComponent(String value) {
        try {
            return java.net.URLEncoder.encode(value, "UTF-8");
        } catch (Exception e) {
            throw new RuntimeException("Error encoding URL component", e);
        }
    }

    public Map<String, Object> getRouteAndDataCombined(Map<String, String> queryParams, boolean noCache) throws Exception {
        return handleRoute(queryParams, noCache);
    }

    public Map<String, Object> getBaiduRanking() throws Exception {
        Map<String, String> queryParams = Map.of("type", "realtime");
        return getRouteAndDataCombined(queryParams, false);
    }
}
